﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using App.Data;
using App.Core.Extensions;
using System.Web.Services;
using System.IO;


public partial class Pages_Private_ProjectChange : System.Web.UI.Page
{
    protected int _ProjectID = 0;
    protected bool _IsEditMode = false;
    protected String _UnitName = String.Empty;
    protected int _SubscriptionID = 0; 

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            if (IsSubscribedToPackage())
            {
                BindDorpdownLists();
                if (_ProjectID == 0)
                    BindContactPersonList(null);
                BindProjectInfo();
                SessionCache.CurrentProjectFiles = null;
            }
        }
    }
    protected void BindPageInfo()
    {
        _ProjectID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        if (_ProjectID > 0)
            _IsEditMode = true;
        if (_IsEditMode)        
            h4Heading.InnerHtml = "Edit Project";
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }
    protected bool IsSubscribedToPackage()
    {
        if (!_IsEditMode)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            var subscription = context.PackageSubscriptions.FirstOrDefault(P => P.CustomerID == SessionCache.CurrentUser.CustomerID && P.ExpireDate >= DateTime.Now);
            if (subscription == null || subscription.ProductCount >= subscription.Projects.Count)
            {
                pnlFormContainer.Visible = false;
                divPackageSubscription.Visible = true;
                return false;
            }
            else
                _SubscriptionID = subscription.ID;
        }
        return true;
    }
    protected void BindDorpdownLists()
    {
        BindDropdownList.ProjectStatuses(ddlProjectStatusID);
        BindDropdownList.Cities(ddlCity, ConfigReader.SiteBusinessCountryID);
        BindDropdownList.PropertyTypes(ddlPropertyTypes, ConfigReader.DeveloperBusinessTypeID);
    }
    protected void BindContactPersonList(int[] selectedIDs)
    {
        BtcHousingEntities context = new BtcHousingEntities();
        var contacts = from P in context.Contacts where P.CustomerID == SessionCache.CurrentUser.CustomerID select P;
        if (contacts != null && contacts.Count() > 0)
        {
            StringBuilder output = new StringBuilder(10);
            for (int i = 0; i < contacts.Count(); i++ )
            {
                Contact contact = contacts.ToList()[i];
                output.Append("<div>");
                output.AppendFormat("<input type=\"checkbox\" id=\"chkContactPerson_{0}\" name=\"chkContactPerson\" value=\"{1}\"{3} /><label for=\"chkContactPerson_{0}\">{2}</label>", i, contact.ID, contact.Name.HtmlEncode()
                    , IsSelectedContact(selectedIDs, contact.ID) ? "checked=\"checked\"": String.Empty);
                output.Append("</div>");
            }
            divContactPersonList.InnerHtml = output.ToString();
        }
    }
    protected void BindProjectInfo()
    {
        if (_IsEditMode)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            Project entity = context.Projects.FirstOrDefault(P => P.ID == _ProjectID);//dao.GetByID(_ID);
            if (entity == null)
                ShowErrorMessage();
            else
            {
                _SubscriptionID = entity.PackageSubscriptionID;
                //ddlCustomerID.SetSelectedItem(entity.CustomerID);
                ddlPropertyTypes.SetSelectedItem(entity.PropertyTypeID.ToString());
                ddlProjectStatusID.SetSelectedItem(entity.ProjectStatusID.ToString());
                txtName.Text = entity.Name;
                txtDescription.Text = entity.Description;
                
                ddlCity.SetSelectedItem(entity.Zone.CityID.ToString());
                BindDropdownList.Zones(ddlZoneID, entity.Zone.CityID);
                ddlZoneID.SetSelectedItem(entity.ZoneID.ToString());

                txtStreetAddress.Text = entity.StreetAddress;
                txtHouseNo.Text = entity.HouseNo;
                txtAddressHint.Text = entity.AddressHint;
                txtNoOfUnits.Text = WebUtil.FormatData(entity.NoOfUnits);
                txtNoOfFloors.Text = WebUtil.FormatData(entity.NoOfFloors);
                txtAvailableUnits.Text = WebUtil.FormatData(entity.AvailableUnits);
                txtArea.Text = WebUtil.FormatData(entity.Area);
                txtAreaOther.Text = entity.AreaOther.HtmlEncode();
                //ddlUnitID.SetSelectedItem(entity.UnitID);
                txtNoOfBeds.Text = WebUtil.FormatData(entity.NoOfBeds);
                chkHasParking.Checked = entity.HasParking;
                chkHasGenerator.Checked = entity.HasGenerator;
                chkHasLift.Checked = entity.HasLift;
                chkHasSecurity.Checked = entity.HasSecurity;
                txtPricePerUnitFrom.Text = WebUtil.FormatForTextBox(entity.PricePerUnitFrom);
                txtPricePerUnitTo.Text = WebUtil.FormatForTextBox(entity.PricePerUnitTo);
                chkHasBookingAvailable.Checked = entity.HasBookingAvailable;
                txtBookingFee.Text = WebUtil.FormatForTextBox(entity.BookingFee);
                chkShowPricingInfo.Checked = entity.ShowPricingInfo;

                _UnitName = entity.Unit.Name.HtmlEncode();
                var contactIDs = from P in context.ProjectContacts where P.ProjectID == entity.ID select P.ContactID;
                if (contactIDs == null || contactIDs.Count() == 0)
                    BindContactPersonList(null);
                else
                    BindContactPersonList(contactIDs.ToArray());

                BindAttachments(entity);            
            }
        }
    }
    /// <summary>
    /// Shows a Message in the UI and Hides the Data Editing Controls
    /// </summary>
    protected void ShowErrorMessage()
    {
        pnlFormContainer.Visible = false;
        WebUtil.ShowMessageBox(divMessage, "Requested Project was not found.", true);
    }
    protected bool IsSelectedContact(int[] selectedIDs, int contactID)
    {
        if (selectedIDs != null && selectedIDs.Length > 0)
        {
            if (selectedIDs.Contains(contactID))
                return true;
        }
        return false;
    }
    protected void BindAttachments(Project project)
    {
        StringBuilder sb = new StringBuilder(10);                
        foreach (ProjectFile file in project.ProjectFiles)
        {
            String fileNameToShow = WebUtil.GetFormattedFileName(file.FileName);
            sb.AppendFormat("<li><a href='{0}/{1}/{2}' target='_blank'>{3}</a> <img onclick='DeleteAttachment({4}, this)' src='/Images/delete.png' style='cursor:pointer;' alt='Delete' title='Delete'/></li>",
                AppConstants.PROJECT_FILES, project.ID, file.FileName, fileNameToShow, file.ID);
        }        
        ltrAttachmentList.Text = sb.ToString();
    }
    [WebMethod]
    public static int SaveProject(App.CustomEntity.Project customeProject)
    {
        BtcHousingEntities context = new BtcHousingEntities();
        Project project = null;
        if (customeProject.ID > 0)
            project = context.Projects.FirstOrDefault(P => P.ID == customeProject.ID);
        else
        {
            project = new Project();
            project.Created = DateTime.Now;            
            context.AddToProjects(project);
        }
        project.Modified = DateTime.Now;
        project.ModifiedBy = SessionCache.CurrentUser.ID;
        project.AddressHint = customeProject.AddressHint;
        project.Area = customeProject.Area;
        project.AreaOther = customeProject.AreaOther;
        project.AvailableUnits = customeProject.AvailableUnits;
        project.BookingFee = customeProject.BookingFee;
        if(project.ID == 0)
            project.CustomerID = SessionCache.CurrentUser.ID;
        project.Description = customeProject.Description;
        project.HasBookingAvailable = customeProject.HasBookingAvailable;
        project.HasGenerator = customeProject.HasGenerator;
        project.HasLift = customeProject.HasLift;
        project.HasParking = customeProject.HasParking;
        project.HasSecurity = customeProject.HasParking;
        project.HouseNo = customeProject.HouseNo;
        project.Name = customeProject.Name;
        project.NoOfBeds = customeProject.NoOfBeds;
        project.NoOfFloors = customeProject.NoOfFloors;
        project.NoOfUnits = customeProject.NoOfUnits;
        project.PricePerUnitFrom = customeProject.PricePerUnitFrom;
        project.PricePerUnitTo = customeProject.PricePerUnitTo;
        project.ProjectStatusID = customeProject.ProjectStatusID;
        project.PropertyTypeID = customeProject.PropertyTypeID;
        project.ShowPricingInfo = customeProject.ShowPricingInfo;
        project.StreetAddress = customeProject.StreetAddress;
        
        var unit = from P in context.UnitOfPropertyTypes where P.PropertyTypeID == project.PropertyTypeID select P.Unit;
        if (unit == null || unit.Count() == 0)
            throw new ArgumentException("Setup Data was not found for UnitOfPropertyType");
        else
            project.UnitID = unit.ToList()[0].ID;

        project.ZoneID = customeProject.ZoneID;

        IList<ProjectFile> files = SessionCache.CurrentProjectFiles;
        foreach (ProjectFile file in files)
        {
            //context.AttachTo("ProjectFiles", file);
            project.ProjectFiles.Add(file);
        }
        if (!customeProject.ContactPersons.IsNullOrEmpty())
        {
            List<String> contacts = customeProject.ContactPersons.Split(',').ToList();
            if (project.ID > 0)
            {
                var projectContacts = project.ProjectContacts;
                foreach (ProjectContact projectContact in projectContacts)
                {
                    if (contacts.Contains(projectContact.ContactID.ToString()))
                        contacts.Remove(projectContact.ContactID.ToString());
                }
            }            
            foreach (String contactId in contacts)
            {
                ProjectContact contact = new ProjectContact();
                contact.ContactID = contactId.ToInt();
                project.ProjectContacts.Add(contact);
            }
        }

        context.SaveChanges();
        
        MoveAttachedFiles(files, context);
        SessionCache.CurrentProjectFiles = null;
        return project.ID;        
    }
    private static void MoveAttachedFiles(IList<ProjectFile> files, BtcHousingEntities context)
    {
        //IList<ProjectFile> files = SessionCache.CurrentProjectFiles;
        foreach (ProjectFile file in files)
        {
            ///Move Files from Temp Directory to User Directory
            String tempFolder = Path.Combine(HttpContext.Current.Server.MapPath(AppConstants.TEMP_DIRECTORY), SessionCache.CurrentUser.ID.ToString());
            String tempFilePath = Path.Combine(tempFolder, file.FileName);
            String actualFilePath = HttpContext.Current.Server.MapPath(AppConstants.PROJECT_FILES);
            actualFilePath = Path.Combine(actualFilePath, file.ProjectID.ToString());
            if (!Directory.Exists(actualFilePath))
                Directory.CreateDirectory(actualFilePath);

            String fileName = String.Format("{0}_{1}", file.ID, file.FileName);
            actualFilePath = Path.Combine(actualFilePath, fileName);

            File.Copy(tempFilePath, actualFilePath, true);
            file.FileName = fileName;            

            ///Move Thumbnail
            String tempThumnail = String.Format("{0}_Thumb{1}", Path.GetFileNameWithoutExtension(tempFilePath), Path.GetExtension(tempFilePath));
            tempThumnail = Path.Combine(Path.GetDirectoryName(tempFilePath), tempThumnail);
            String destinationThumb = String.Format("{0}_Thumb{1}", Path.GetFileNameWithoutExtension(actualFilePath), Path.GetExtension(actualFilePath));
            destinationThumb = Path.Combine(Path.GetDirectoryName(actualFilePath), destinationThumb);
            if (File.Exists(tempThumnail))
            {
                File.Copy(tempThumnail, destinationThumb);
                File.Delete(tempThumnail);
                file.ThumbFileName = Path.GetFileName(destinationThumb);
            }
            ///Delete Temporay File
            if (File.Exists(tempFilePath))
                File.Delete(tempFilePath);
        }
        context.SaveChanges();
    }

    [WebMethod]
    public static bool DeleteProjectAttachment(int fileId, String fileName)
    {
        BtcHousingEntities context = new BtcHousingEntities();
        ProjectFile file = context.ProjectFiles.FirstOrDefault(F => F.ID == fileId);
        if (file == null)
        {
            ///Deleting Attachement in Enquiry Add Mode
            if (!fileName.IsNullOrEmpty())
            {
                if (fileName.StartsWith(".."))
                    fileName = fileName.Replace("..", String.Empty);
                fileName = HttpContext.Current.Server.MapPath(fileName);
                ///Delete File
                if (File.Exists(fileName))
                    File.Delete(fileName);
                ///Delete Thumbnail
                String thumnail = String.Format("{0}_Thumb{1}", Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
                thumnail = Path.Combine(Path.GetDirectoryName(fileName), thumnail);
                if (File.Exists(thumnail))
                    File.Delete(thumnail);

                fileName = Path.GetFileName(fileName);
                RemoveAttachmentFromSession(fileName);
            }
        }
        else
        {
            String filePath = Path.Combine(HttpContext.Current.Server.MapPath(AppConstants.PROJECT_FILES), String.Format(@"{0}\{1}", file.ProjectID, file.FileName));
            if (File.Exists(filePath))
                File.Delete(filePath);

            ///Delete Thumbnail
            String thumnail = String.Format("{0}_Thumb{1}", Path.GetFileNameWithoutExtension(filePath), Path.GetExtension(filePath));
            thumnail = Path.Combine(Path.GetDirectoryName(filePath), thumnail);
            if (File.Exists(thumnail))
                File.Delete(thumnail);

            //context.ProjectFiles.DeleteOnSubmit(file);
            context.DeleteObject(file);
            //context.SubmitChanges();
            context.SaveChanges();
            RemoveAttachmentFromSession(Path.GetFileName(filePath));
            return true;
        }
        return false;
    }
    public static void RemoveAttachmentFromSession(String fileName)
    {
        IList<ProjectFile> files = SessionCache.CurrentProjectFiles;
        ProjectFile attachment = files.FirstOrDefault(F => F.FileName == fileName);
        if (attachment != null)
        {
            files.Remove(attachment);
            SessionCache.CurrentProjectFiles = files;
        }
    }
}